#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif

int main(int argc, char **argv){
    int fd, openFlags;
    mode_t filePerms;
    char buf[BUF_SIZE];
    ssize_t readCount;

    if (argc == 3){
        if(strcmp(argv[2], "-a") == 0){
           openFlags = O_WRONLY | O_APPEND;
           filePerms = 0;
        }
        else{
            puts("You ust use filename -a");
            exit(EXIT_FAILURE);
        }
    }
    else if(argc == 2){
           openFlags = O_WRONLY | O_CREAT | O_TRUNC ;
           filePerms = S_IRUSR | S_IWUSR | S_IWGRP | S_IROTH;
    }
    else{
        printf("You must use my_tee filename or my_tee filename -a");
        exit(EXIT_FAILURE);
    }
    
    fd = open(argv[1], openFlags, filePerms); 
    if (fd == -1){
        printf("Error open file %s\n", argv[1]);
        perror("");
        exit(EXIT_FAILURE);
    }
    while( (readCount = read(STDIN_FILENO, buf, BUF_SIZE)) != 0 ){// EOF
        if (readCount == -1){
            perror("Error read from stdin");
            exit(EXIT_FAILURE);           
        }
        if (write(STDOUT_FILENO, buf, readCount) == -1){
            perror("Error write stdout");
            exit(EXIT_FAILURE);              
        }
        if(write(fd, buf, readCount) == -1){
            printf("Error write to file %s\n", argv[1]);
            perror("");
            exit(EXIT_FAILURE);   
        }
    }
    if (close(argv[1]) == -1){
        printf("Error close file %s\n", argv[1]);
        perror("");
        exit(EXIT_FAILURE);          
    }
    exit(EXIT_SUCCESS);

}